﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using GemBox.Spreadsheet;

using AppDialogBox;

namespace PasswordControl
{
    static public class ImportExport
    {
        static public string path;
        static public string name;
        static public string[] property_list = { "Name", "Username", "Password", "Opional Field" };
        static bool to_gorups = true;


        static public void CreateTemplate()
        {
            try
            {
                int index;
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.Description = "Choose the folder you want the output file in:";
                if (fbd.ShowDialog() == DialogResult.Cancel) return;
                path = fbd.SelectedPath;
                name = "Import Template";
                string full_path = path + @"\" + name;

                //style object
                CellStyle mystyle = new CellStyle();
                SetStyleTop(mystyle);
                CellStyle borderstyle = new CellStyle();

                //create xlsx file and add a worksheet
                ExcelFile excelFile = new ExcelFile();
                ExcelWorksheet ws1 = excelFile.Worksheets.Add("Password Control");

                ws1.Cells.GetSubrangeRelative(0, 0, property_list.Length, 2).Style = mystyle;
                ws1.Cells.GetSubrangeRelative(0, 0, property_list.Length, 1).Merged = true;
                ws1.Cells[0, 0].Value = "Password Table";
                for (index = 0; index < property_list.Length; index++)
                {
                    ws1.Columns[index].Width = 20 * 256;
                    ws1.Cells[1, index].Value = property_list[index];
                }
                ws1.Rows[0].Height = 20 * 20;

                CreateImportRows(ws1, 50);

                //group border
                ws1.Columns[4].Width = 3 * 256;
                ws1.Cells.GetSubrangeRelative(0, 4, 1, 100 + 2).Merged = true;
                SetGroupBorder(borderstyle);
                ws1.Cells.GetSubrangeRelative(0, 4, 1, 100 + 2).Style = borderstyle;

                excelFile.SaveXlsx(full_path + ".xlsx");
                excelFile.ClosePreservedXlsx();
            }
            catch//(Exception e)
            {
                //MessageBox.Show(e.Message, "Import File Error");
                AppDialogWrapper.PromptBox("Import file wasn't created, \ncheck if file already opened or exists","Import File Error");
                return;
            }
        }
        static public void Import()
        {
            try
            {
                Owners owner;

                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.Description = "Choose the folder to look in for 'Import Template.xlsx':";
                if (fbd.ShowDialog() == DialogResult.Cancel) return;
                path = fbd.SelectedPath;
                name = "Import Template";
                string full_path = path + @"\" + name;

                ExcelFile excelFile = new ExcelFile();
                excelFile.LoadXlsx(full_path + ".xlsx", XlsxOptions.None);

                ExcelWorksheet ws = excelFile.Worksheets[0];

                //here i need to take the data
                for (int row = 2; row < 102; row += 2)
                {
                    if (ws.Cells[row, 0].Value != null && ws.Cells[row,0].Value.ToString() != "" )
                    {
                        owner = new Owners();
                        owner.Owner = ws.Cells[row, 0].Value.ToString();

                        if (ws.Cells[row, 1].Value != null) owner.Username = ws.Cells[row, 1].Value.ToString();
                        if (ws.Cells[row, 2].Value != null) owner.Password = ws.Cells[row, 2].Value.ToString();
                        if (ws.Cells[row, 3].Value != null) owner.Fieldname = ws.Cells[row, 3].Value.ToString();
                        if (ws.Cells[row+1, 3].Value != null) owner.Fielddata = ws.Cells[row+1, 3].Value.ToString();

                        Owners.AddOwner(owner);
                    }
                }

                excelFile.ClosePreservedXlsx();
            }
            catch//(Exception e)
            {
                //MessageBox.Show(e.Message, "Import Error");
                AppDialogWrapper.PromptBox("Data couldn't be imported, \nthe template file may be opened or doesn't exist", "Import Error");
                return;
            } 
        }


        static public void Export(List<Owners> data)
        {
            try
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                fbd.Description = "Choose the folder you want the output file in:";
                if (fbd.ShowDialog() == DialogResult.Cancel) return;
                path = fbd.SelectedPath;
                name = "Password Control";
                string full_path = path + @"\" + name;

                int index, group, column;
                List<List<Owners>> group_list = BreakGroups(data);
                switch (AppDialogWrapper.PromptBox("Do you want the passwords to be arranged by thier groups?", "Output Style", MessageBoxButtons.YesNoCancel))
                {
                    case DialogResult.Cancel:
                        return;
                    case DialogResult.No:
                        group_list.Clear();
                        group_list.Add(data);
                        to_gorups = false;
                        break;
                    case DialogResult.Yes:
                        break;
                }

                //style object
                CellStyle mystyle = new CellStyle();
                SetStyleTop(mystyle);
                CellStyle borderstyle = new CellStyle();


                //create xlsx file and add a worksheet
                ExcelFile excelFile = new ExcelFile();
                ExcelWorksheet ws1 = excelFile.Worksheets.Add("Password Control");

                for (group = 0; group < group_list.Count; group++)
                {
                    column = group * 5;

                    //create basic table 
                    ws1.Cells.GetSubrangeRelative(0, column, property_list.Length, 2).Style = mystyle;
                    ws1.Cells.GetSubrangeRelative(0, column, property_list.Length, 1).Merged = true;
                    for (index = 0; index < property_list.Length; index++)
                    {
                        ws1.Columns[index+column].Width = 20 * 256;
                        ws1.Cells[1, index+column].Value = property_list[index];
                    }
                    ws1.Rows[0].Height = 20 * 20;

                    //rows...
                    for (index = 0; index < group_list[group].Count; index++)
                    {
                        CreateRow(ws1, index + 1, group_list[group][index], column);
                        if (to_gorups)
                        {
                            if (index == 0) ws1.Cells[0, column].Value = group_list[group][index].Group;
                        }
                        else
                            ws1.Cells[0, column].Value = "Password List";
                    }

                    //group border
                    ws1.Columns[column + 4].Width = 3 * 256;
                    ws1.Cells.GetSubrangeRelative(0, column + 4, 1, index*2+2).Merged = true;
                    SetGroupBorder(borderstyle);
                    ws1.Cells.GetSubrangeRelative(0, column + 4, 1, index*2+2).Style = borderstyle;
                }

                excelFile.SaveXlsx(full_path + ".xlsx");
                excelFile.ClosePreservedXlsx();
            }
            catch//(Exception e)
            {
                //MessageBox.Show(e.Message,"Export Error");
                AppDialogWrapper.PromptBox("Export file wasn't created,  \ncheck if file already opened or exists","Export Error");
                return;
            }
        }

        //set top style
        static private void SetStyleTop(CellStyle mystyle)
        {
            mystyle.HorizontalAlignment = HorizontalAlignmentStyle.Center;
            mystyle.VerticalAlignment = VerticalAlignmentStyle.Center;
            mystyle.FillPattern.SetSolid(Color.Chocolate);
            mystyle.Font.Weight = ExcelFont.BoldWeight;
            mystyle.Font.Size = 14 * 20;
            mystyle.Font.Color = Color.White;
            mystyle.WrapText = true;
            mystyle.Borders.SetBorders(MultipleBorders.Right | MultipleBorders.Top, Color.Black, LineStyle.Thin);
            mystyle.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);

        }
        //set row style
        static private CellStyle SetRowStyle(int index)
        {
            CellStyle mystyle = new CellStyle();

            mystyle.HorizontalAlignment = HorizontalAlignmentStyle.Center;
            mystyle.VerticalAlignment = VerticalAlignmentStyle.Center;

            if (index % 2 == 0)
                mystyle.FillPattern.SetSolid(Color.LightSkyBlue);
            else
                mystyle.FillPattern.SetSolid(Color.FromArgb(210, 210, 230));

            mystyle.Font.Color = Color.Black;
            mystyle.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);


            return mystyle;
        }
        //set group border
        static private void SetGroupBorder(CellStyle borderstyle)
        {
            borderstyle.FillPattern.SetSolid(Color.Olive);
            borderstyle.Borders.SetBorders(MultipleBorders.Outside, Color.Black, LineStyle.Thin);
        }


        //create row
        static private void CreateRow(ExcelWorksheet ws, int index, Owners owner, int rcolumn)
        {
            int row = 2 * index;
            CellStyle mystyle = SetRowStyle(index);

            ws.Rows[row].Height = 20 * 20;
            ws.Rows[row + 1].Height = 20 * 20;

            ws.Cells.GetSubrangeRelative(row, rcolumn, property_list.Length, 2).Style = mystyle;

            //merge needed cells
            for (int colomn = 0; colomn < property_list.Length; colomn++)
            {
                if (colomn < 3)
                {
                    ws.Cells.GetSubrangeRelative(row, colomn + rcolumn, 1, 2).Merged = true;
                    ws.Cells.GetSubrangeRelative(row, colomn + rcolumn, 1, 2).Style.Font.Size = 16 * 20;
                }
                else
                {
                    ws.Cells[row, colomn + rcolumn].Style.Font.Size = 13 * 20;
                    ws.Cells[row + 1, colomn + rcolumn].Style.Font.Size = 13 * 20;
                }
            }
            //insert data to cells
            ws.Cells[row, 0+rcolumn].Value = owner.Owner; ws.Cells[row, 1+rcolumn].Value = owner.Username; ws.Cells[row, 2+rcolumn].Value = owner.Password;
            ws.Cells[row, 3+rcolumn].Value = owner.Fieldname; ws.Cells[row + 1, 3+rcolumn].Value = owner.Fielddata;
        }
        //create import row
        static private void CreateImportRows(ExcelWorksheet ws, int count)
        {
            int row;
            CellStyle mystyle;

            for (int i = 1; i <= count; i++)
            {
                row = i * 2;
                mystyle = SetRowStyle(i);

                ws.Rows[row].Height = 20 * 20;
                ws.Rows[row + 1].Height = 20 * 20;

                ws.Cells.GetSubrangeRelative(row, 0, property_list.Length, 2).Style = mystyle;

                for (int colomn = 0; colomn < property_list.Length; colomn++)
                {
                    if (colomn < 3)
                    {
                        ws.Cells.GetSubrangeRelative(row, colomn, 1, 2).Merged = true;
                        ws.Cells.GetSubrangeRelative(row, colomn, 1, 2).Style.Font.Size = 16 * 20;
                    }
                    else
                    {
                        ws.Cells[row, colomn].Style.Font.Size = 13 * 20;
                        ws.Cells[row + 1, colomn].Style.Font.Size = 13 * 20;
                    }
                }
            }
        }

        //break to groups
        static private List<List<Owners>> BreakGroups(List<Owners> data)
        {
            int index;
            List<List<Owners>> group_list = new List<List<Owners>>();
            List<string> group_index = new List<string>();

            foreach (Owners temp in data)
            {
                if (!group_index.Contains(temp.Group))
                {
                    if (temp.Group == ControlProgram.GROUP_GENERAL)
                    {
                        group_index.Insert(0, temp.Group);
                        group_list.Insert(0 , new List<Owners>());
                    }
                    else
                    {
                        group_index.Add(temp.Group);
                        group_list.Add(new List<Owners>());
                    }
                }
                for (index = 0; index < group_index.Count; index++)
                {
                    if (group_index[index].ToString() == temp.Group)
                        break;
                }
                group_list[index].Add(temp);
            }
            return group_list;
        }
    }
}

